package com.example.administrator.q1;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Calendar;

import static java.util.TimeZone.getTimeZone;

/**
 * Created by Administrator on 2017/9/1.
 */

public class FragmentFour extends Fragment{

    TextView timeTextView;

    final int what = 1;

    String [] weeks = {"日","日","一","二","三","四","五","六"};

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view= inflater.inflate(R.layout.fragment_fragment_four, null);

        timeTextView = (TextView)view.findViewById(R.id.timeTextView);



        new MyThread().start();
        timeTextView.setText(getTime());

        return view;
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Message msg = new Message();
                    msg.what = what;
                    handler.sendMessage(msg);
                    // sendMessage(getTime());
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        }
    }

    private Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    timeTextView.setText(getTime());
                    break;
            }
        }
    };

    public void sendMessage(String message) {
        timeTextView.setText(message);
    }

    public String getTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(getTimeZone("GMT+8:00"));
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.valueOf(calendar.get(Calendar.MONTH));
        String date = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        String hour = String.valueOf(calendar.get(Calendar.HOUR));
        String minute = String.valueOf(calendar.get(Calendar.MINUTE));
        String second = String.valueOf(calendar.get(Calendar.SECOND));
        int week = calendar.get(Calendar.DAY_OF_WEEK);

        String time = year + "/" + month + "/" + date + hour + ":" + minute + ":" +second + "..." + "星期" + weeks[week];

        return time;
    }
}
